#pragma once
#include <iostream>
#include <string>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <cstdint>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
using namespace std;
const int size = 1024;
string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;
class udpserver{
    public:
    udpserver(const uint16_t& port = defaultport,string& ip = defaultip)
    :port_(port)
    ,ip_(ip)
    {

    }
void Init(){
        sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(sockfd<0){
            cout<<strerror(errno)<<endl;
            exit(1);
        }
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        //对该自定义类型进行填充
        local.sin_family = AF_INET;//传输类型
        local.sin_port = htons(port_);//主机转网络序列
        //local.sin_addr.s_addr = inet_addr(ip_.c_str());//填充ip，为方便用户一边设置ip为string，但ip填充要求为，先将ip转为uint32_t
        local.sin_addr.s_addr = INADDR_ANY;//本质上就是0被定义了，全0的ip就是交给该电脑的任意ip都可接收，防止有多个ip只能接收一个ip。
        if(bind(sockfd,(const struct sockaddr*)&local,sizeof(local))<0){//将套接字进行填充
            cout<<strerror(errno)<<endl;
            exit(1);
        }
        cout<<"success"<<endl;
}
void Run(){
isruning_ = true;
char inbuffer[size];

while(true){
    struct sockaddr_in client;
    socklen_t len = sizeof(client);
    cout<<"接收"<<endl;
    ssize_t n = recvfrom(sockfd,inbuffer,sizeof(inbuffer)-1,0,(struct sockaddr*)&client,&len);
    cout<<n<<endl;//接收客户端发来的消息
    if(n<0){
         cout<<strerror(errno)<<endl;
         continue;
    }
    inbuffer[n] = 0;
    //处理数据
    std::string info = inbuffer;
    string echo_string = "server echo#" + info;
    cout<<echo_string<<endl;
    sendto(sockfd,echo_string.c_str(),echo_string.size(),0,(struct sockaddr*)&client,len);
}
}
private:
int sockfd;
string ip_;
uint16_t port_;
bool isruning_;
};